<template>
	<view class="container" :class="{ 'tablet-layout': isTablet }">
		<!-- 头部卡片 - 包含基本信息 -->
		<view class="header-card-c">
			<view class="button-group">
				<!-- 			<button class="btn btn-primary" @click="handleScanWeigh">
					<uni-icons type="scan" size='mini' color="#fff"></uni-icons>
					扫码称重
				</button> -->
				<button class="btn btn-secondary" @click="handleSearchCode">
					<uni-icons type="search" size='mini' color="#fff"></uni-icons>
					扫码称重
				</button>
				<button class="btn-c" style="margin-left: auto;" @click="handleRefresh">
					<uni-icons type="refresh" size='mini' color="#757575"></uni-icons>
					刷新
				</button>
				<!-- 	<button class="btn-c" type="primary" @click="storage">
					<uni-icons type="folder" size='mini' color="#fff"></uni-icons>
					暂存
				</button> -->
				<button class="btn-c" type="primary" style="margin-right:0;background-color: #0a9403;"
					v-if="weighingMasterList.billNo" @click="generate">
					<uni-icons type="checkmark" size='mini' color="#fff"></uni-icons>
					生成称重单
				</button>
			</view>
		</view>
		<!-- 物料表格 -->
		<view class="material-table-container">

			<!-- 头部卡片 - 包含基本信息 -->
			<view class="header-card-a" v-if="data.billNo">
				<view class="basic-info-grid">
					<view class="basic-info-item">
						<text class="basic-info-label">单据号 : {{ weighingMasterList.billNo || '-' }}</text>
					</view>
					<view class="basic-info-item">
						<text class="basic-info-label">单据日期 : {{ pasTime(weighingMasterList.billDate) || '-' }}</text>
					</view>
					<view class="basic-info-item">
						<text class="basic-info-label">来源工单号 : {{ data.billNo || '-' }}</text>
					</view>
					<view class="basic-info-item">
						<text class="basic-info-label">母件 : {{ data.materialId || '-' }}</text>
					</view>
					<text class="table-count" style="margin-left: auto;">共 {{ data.details.length }} 项</text>
				</view>
			</view>
			<!-- 使用 uni-table 组件 -->
			<uni-table border stripe emptyText="暂无数据">
				<uni-tr>
					<uni-th width="100" align="center">子件代码</uni-th>
					<uni-th width="100" align="center">物料名称</uni-th>
					<uni-th width="100" align="center">比例</uni-th>
					<uni-th width="100" align="center">比例用量</uni-th>
					<uni-th width="100" align="center">称重量</uni-th>
					<uni-th width="100" align="center">工单累计称重</uni-th>
					<uni-th width="50" align="center">单位</uni-th>
					<uni-th width="100" align="center">料属性</uni-th>
					<!-- <uni-th width="100" align="center">本次累计称重</uni-th> -->
					<uni-th width="50" align="center">子件规格</uni-th>
					<!-- <uni-th width="50" align="center">密度</uni-th> -->
					<!-- <uni-th width="120" align="center">子件用量类型</uni-th> -->
					<!-- <uni-th width="80" align="center">母件基数</uni-th> -->
					<!-- <uni-th width="60" align="center">损耗率</uni-th> -->
					<!-- <uni-th width="50" align="center">用量</uni-th> -->
					<!-- <uni-th width="80" align="center">未领数量</uni-th> -->
					<uni-th width="70" align="center">称重人</uni-th>
					<!-- <uni-th width="100" align="center">称重日期</uni-th> -->
					<uni-th width="40" align="center">称重</uni-th>

					<uni-th width="40" align="center">主胶</uni-th>
				</uni-tr>
				<uni-tr v-if="Loading">
					<uni-td :colspan="17" align="center">
						<view class="loading-container">
							<uni-load-more status="loading" content="加载中..."></uni-load-more>
						</view>
					</uni-td>
				</uni-tr>
				<uni-tr v-for="(material, index) in data.details" :key="index">
					<uni-td title='子件代码' align="center">{{ material.subMaterialId || '-' }}</uni-td>
					<uni-td title='物料名称' align="center">{{ material.materialName || '-' }}</uni-td>
					<uni-td title='比例' align="center">{{ material.bl || '-' }}%</uni-td>
					<uni-td title='比例用量' align="center">{{ upper(material.upper, material.lower) || '-' }}</uni-td>
					<uni-td title='称重量' align="center">{{ cuQuantity(material.weighingDetailList).cuQuantity || '-'
					}}</uni-td>
					<uni-td title='本次累计称重' align="center">{{ cuQuantity(material.weighingDetailList).cumulativeQuantity
						|| '-' }}</uni-td>
					<uni-td title='单位' align="center">{{ material.unitId || '-' }}</uni-td>
					<uni-td title='料属性' align="center">{{ material.materialType || '-' }}</uni-td>


					<!-- <uni-td title='工单累计称重'
						align="center">{{ cuQuantity(material.weighingDetailList ).cuTotalQuantity || '-' }}</uni-td> -->
					<uni-td title='子件规格' align="center">{{ material.subMaterialSpec || '-' }}</uni-td>
					<!-- <uni-td title='密度' align="center">{{ null || '-' }}</uni-td> -->
					<!-- <uni-td title='子件用量类型' align="center">{{ null || '-' }}</uni-td> -->
					<!-- <uni-td title='母件基数' align="center">{{ null || '-' }}</uni-td> -->
					<!-- <uni-td title='损耗率' align="center">{{ null || '-' }}</uni-td> -->
					<!-- <uni-td title='用量' align="center">{{ material.produceNeedQty || '-' }}</uni-td> -->
					<!-- <uni-td title='未领数量' align="center">{{ material.remainTakeQty || '-' }}</uni-td> -->

					<uni-td title='称重人' align="center">{{ getCreatorName(material) || '-' }}</uni-td>
					<!-- <uni-td title='称重日期' align="center">{{
						convertGMTToChinaTime(cuQuantity(material.weighingDetailList).cuCzTime) }}</uni-td> -->
					<uni-td title='称重' align="center">
						<view class="status-tag" :class="getMaterialStatusClass(material.isWeighing)">
							{{ getMaterialStatusText(material.isWeighing) }}
						</view>
					</uni-td>
					<uni-td title='主胶' align="center">
						<view class="status-tag" :class="getMaterialStatusClass(material.isMainMaterial)">
							{{ getMaterialStatusText(material.isMainMaterial) }}
						</view>
					</uni-td>
				</uni-tr>
			</uni-table>
		</view>
		<uni-section title="历史称重记录" type="line">
			<view v-if="weighingMasterListFinished && weighingMasterListFinished.length > 0">
				<uni-collapse v-model="valueCollapse" @change="handleCollapseChange" accordion>
					<uni-collapse-item v-for="(item, index) in weighingMasterListFinished" :key="index"
						:title="item.billNo" :name="item.billNo" @title-click="handleItemClick(item)">
						<view class="content">
							<uni-table border stripe emptyText="暂无数据">
								<uni-tr>
									<!-- <uni-th width="100" align="center">子件代码</uni-th>
									<uni-th width="100" align="center">物料名称</uni-th>
									<uni-th width="50" align="center">子件规格</uni-th>
									<uni-th width="50" align="center">密度</uni-th>
									<uni-th width="120" align="center">子件用量类型</uni-th>
									<uni-th width="80" align="center">母件基数</uni-th>
									<uni-th width="50" align="center">单位</uni-th>
									<uni-th width="60" align="center">损耗率</uni-th>
									<uni-th width="100" align="center">料属性</uni-th>
									<uni-th width="70" align="center">用量</uni-th>
									<uni-th width="70" align="center">称重量</uni-th>
									<uni-th width="50" align="center">用量</uni-th>
									<uni-th width="80" align="center">未领数量</uni-th>
									<uni-th width="40" align="center">称重</uni-th>
									<uni-th width="70" align="center">称重人</uni-th>
									<uni-th width="40" align="center">主胶</uni-th> -->

									<uni-th width="100" align="center">子件代码</uni-th>
									<uni-th width="100" align="center">物料名称</uni-th>
									<uni-th width="100" align="center">比例</uni-th>
									<uni-th width="100" align="center">比例用量</uni-th>
									<uni-th width="100" align="center">称重量</uni-th>
									<!-- <uni-th width="100" align="center">本次累计称重</uni-th> -->
									<uni-th width="100" align="center">工单累计称重</uni-th>
									<uni-th width="50" align="center">单位</uni-th>
									<uni-th width="100" align="center">料属性</uni-th>
									<uni-th width="50" align="center">子件规格</uni-th>
									<!-- <uni-th width="50" align="center">密度</uni-th> -->
									<!-- <uni-th width="120" align="center">子件用量类型</uni-th> -->
									<!-- <uni-th width="80" align="center">母件基数</uni-th> -->
									<!-- <uni-th width="60" align="center">损耗率</uni-th> -->
									<!-- <uni-th width="50" align="center">用量</uni-th> -->
									<!-- <uni-th width="80" align="center">未领数量</uni-th> -->
									<uni-th width="70" align="center">称重人</uni-th>
									<uni-th width="100" align="center">称重日期</uni-th>
									<uni-th width="40" align="center">称重</uni-th>

									<uni-th width="40" align="center">主胶</uni-th>
								</uni-tr>
								<uni-tr v-if="tabloading2">
									<uni-td :colspan="17" align="center">
										<view class="loading-container">
											<uni-load-more status="loading" content="加载中..."></uni-load-more>
										</view>
									</uni-td>
								</uni-tr>
								<uni-tr v-for="(material, materialIndex) in weighingMasterListFinishedDetail"
									:key="materialIndex">
									<!-- <uni-td title='子件代码' align="center">{{ material.produceOrderDetail.subMaterialId ||
										'-' }}</uni-td>
									<uni-td title='物料名称' align="center">{{ material.produceOrderDetail.materialName ||
										'-' }}</uni-td>
									<uni-td title='子件规格' align="center">{{ material.produceOrderDetail.subMaterialSpec
										|| '-' }}</uni-td>
									<uni-td title='密度' align="center">{{ null || '-' }}</uni-td>
									<uni-td title='子件用量类型' align="center">{{ null || '-' }}</uni-td>
									<uni-td title='母件基数' align="center">{{ null || '-' }}</uni-td>
									<uni-td title='单位' align="center">{{ material.produceOrderDetail.unitId || '-'
									}}</uni-td>
									<uni-td title='损耗率' align="center">{{ null || '-' }}</uni-td>
									<uni-td title='料属性' align="center">{{ material.produceOrderDetail.materialType ||
										'-' }}</uni-td>
									<uni-td title='用量' align="center">{{ null || '-' }}</uni-td>
									<uni-td title='称重量' align="center">{{ material.cuQuantity || '-' }}</uni-td>
									<uni-td title='用量' align="center">{{ material.produceOrderDetail.produceNeedQty ||
										'-' }}</uni-td>
									<uni-td title='未领数量' align="center">{{ material.produceOrderDetail.remainTakeQty ||
										'-' }}</uni-td>
									<uni-td title='称重' align="center">
										<view class="status-tag"
											:class="getMaterialStatusClass(material.produceOrderDetail.isWeighing)">
											{{ getMaterialStatusText(material.produceOrderDetail.isWeighing) }}
										</view>
									</uni-td>
									<uni-td title='称重人' align="center">{{ material.creatorName || '-' }}</uni-td>
									<uni-td title='主胶' align="center">
										<view class="status-tag"
											:class="getMaterialStatusClass(material.produceOrderDetail.isMainMaterial)">
											{{ getMaterialStatusText(material.produceOrderDetail.isMainMaterial) }}
										</view>
									</uni-td> -->





									<uni-td title='子件代码' align="center">{{ material.produceOrderDetail.subMaterialId ||
										'-' }}</uni-td>
									<uni-td title='物料名称' align="center">{{ material.produceOrderDetail.materialName ||
										'-' }}</uni-td>
									<uni-td title='比例' align="center">{{ material.bl || '-' }}</uni-td>
									<uni-td title='比例用量' align="center">{{ material.blyl || '-' }}</uni-td>
									<uni-td title='称重量' align="center">{{ material.cuQuantity || '-' }}</uni-td>

									<uni-td title='本次累计称重' align="center">{{
										material.cumulativeQuantity
										|| '-' }}</uni-td>
									<uni-td title='单位' align="center">{{ material.produceOrderDetail.unitId || '-'
									}}</uni-td>
									<uni-td title='料属性' align="center">{{ material.produceOrderDetail.materialType ||
										'-' }}</uni-td>
									<!-- <uni-td title='工单累计称重'
						align="center">{{ cuQuantity(material.weighingDetailList ).cuTotalQuantity || '-' }}</uni-td> -->
									<uni-td title='子件规格' align="center">{{ material.produceOrderDetail.subMaterialSpec
										|| '-' }}</uni-td>
									<!-- <uni-td title='密度' align="center">{{ null || '-' }}</uni-td> -->
									<!-- <uni-td title='子件用量类型' align="center">{{ null || '-' }}</uni-td> -->
									<!-- <uni-td title='母件基数' align="center">{{ null || '-' }}</uni-td> -->

									<!-- <uni-td title='损耗率' align="center">{{ null || '-' }}</uni-td> -->
									<!-- <uni-td title='用量' align="center">{{ material.produceNeedQty || '-' }}</uni-td> -->
									<!-- <uni-td title='未领数量' align="center">{{ material.remainTakeQty || '-' }}</uni-td> -->

									<uni-td title='称重人' align="center">{{ material.creatorName || '-' }}</uni-td>
									<uni-td title='称重日期' align="center">{{
										convertGMTToChinaTime(material.cuCzTime) }}</uni-td>
									<uni-td title='称重' align="center">
										<view class="status-tag"
											:class="getMaterialStatusClass(material.produceOrderDetail.isWeighing)">
											{{ getMaterialStatusText(material.produceOrderDetail.isWeighing) }}
										</view>
									</uni-td>
									<uni-td title='主胶' align="center">
										<view class="status-tag"
											:class="getMaterialStatusClass(material.produceOrderDetail.isMainMaterial)">
											{{ getMaterialStatusText(material.produceOrderDetail.isMainMaterial) }}
										</view>
									</uni-td>
								</uni-tr>
							</uni-table>
						</view>
					</uni-collapse-item>
				</uni-collapse>
			</view>
			<view class="content" v-else>
				<uni-table border stripe>
				</uni-table>
			</view>
		</uni-section>
		<showInputPop :show.sync="showPopup" title="物料编码查询" label="物料编码" placeholder="请输入物料编码" @confirm="onConfirm"
			@close="onClose" />

		<workDetailsInfo :show="showInfoPopup" :infoData="materialInfo" :userInfo="userInfo" :user="userAdmin"
			:showTosdata="showTosdata" title="物料详细信息" cancelText="关闭" confirmText="确定" @close="infoClose"
			@confirm="handleConfirm" @confirms="handleConfirms" @password-change="onPasswordChange"
			@user-change="onUserChange" @update:userInfo="onUserInfoUpdate" />
		<loading :show="Loading" />
	</view>
</template>

<script>
import showInputPop from '@/components/showInputPop.vue';
import loading from '@/components/loading/loading.vue';
import workDetailsInfo from '@/components/workDetailsInfo.vue';
import {
	addWeighingDetail,
	getWorkDetail,
	getcheckSubMaterial,
	updateCurrentWeight,
	weighingMasterFinished,
	updateCurrentWeightUser,
	getcheckWeighingWeigh
} from '@/api/work/workDetails'
import {
	formatShanghaiTime
} from '@/utils/timeShanghai';
import scanCodeUtils from '@/utils/scanCodeUtils';
import {
	showConfirm,
	toast
} from '@/utils/common';
export default {
	components: {
		showInputPop,
		loading,
		workDetailsInfo
	},
	data() {
		return {
			userAdmin: true,
			showTosdata: null,
			userInfo: {
				userName: '',
				passWord: ''
			},
			valueCollapse: [],
			weighingMasterListFinishedDetail: [],
			previousCollapse: [], // 保存之前的状态
			Loading: false,
			tabloading2: false,
			workId: null,
			weighingMasterList: [],
			weighingMasterListFinished: [],
			isTablet: false,
			showPopup: false,
			showInfoPopup: false,
			materialInfo: null,
			valueCollapse: ['0'],
			data: {

			}
		}
	},
	computed: {
		Weight() {
			return this.$store.state.user.CurrentWeight;
		}
	},

	onLoad(options) {
		console.log(options)
		this.checkDeviceType();
		if (options.workId) {
			this.workId = options.workId
			this.queryWorkDetailinfo(this.workId);
		}
		console.log(this.Weight, 'this.$store.state.user.CurrentWeight;');
	},
	created() {
		console.log(this.$store.weight);
		this.$store.commit('SET_WEIGHT', 1);
	},
	methods: {
		upper(item1, item2) {
			// 处理所有可能的空值情况
			if (!item1 && !item2) {
				return '-';
			}

			// 将值转换为字符串并去除首尾空格
			const str1 = item1 ? String(item1).trim() : '';
			const str2 = item2 ? String(item2).trim() : '';

			// 如果有一个为空，只返回非空的那个
			if (!str1) {
				return str2 || '-';
			}
			if (!str2) {
				return str1 || '-';
			}

			// 两个都有值，用连接符连接
			return `${str2}-${str1}`;
		},

		getCreatorName(item) {
			return item.weighingDetailList && item.weighingDetailList.length > 0 ? item.weighingDetailList[0]
				.creatorName : '-';
		},

		// 处理折叠项点击事件
		handleItemClick(item) {
			console.log('点击的账单号:', item.billNo)
		},



		// storage() {
		// 	console.log('点击暂存')
		// },
		generate() {















			// 检查所有需要称重的项目是否都有累计数量值
			const allHaveValue = this.data.details.every(item => {
				// 只有需要称重的项目才检查
				if (item.isWeighing) {
					const cumulativeQuantity = this.cuQuantity(item.weighingDetailList).cumulativeQuantity;
					console.log(cumulativeQuantity);
					// 检查 cumulativeQuantity 是否有值（可以为0，但不能为空）
					return cumulativeQuantity != null && cumulativeQuantity !== '' && cumulativeQuantity !==
						undefined;
				}
				// 不需要称重的项目直接返回 true
				return true;
			});

			if (allHaveValue) {
				console.log('所有需要称重的项目累计数量都有值，开始调用接口');




				showConfirm('确定完成当前称重单？')
					.then(res => {
						if (res.confirm) {
							console.log('用户点击了确定');
							this.Loading = true
							weighingMasterFinished(this.weighingMasterList.billNo).then(res => {
								console.log(res);
								this.queryWorkDetailinfo(this.workId);
							}).catch(err => {
								console.log(err);
								this.Loading = false
							})
						} else if (res.cancel) {
							console.log('用户点击了取消');
							// 执行取消后的操作
						}
					})
					.catch(error => {
						console.error('弹窗出错:', error);
					});






			} else {
				toast('存在未完成称重的物料')
			}
		},
		handleRefresh() {
			this.queryWorkDetailinfo(this.workId);
		},

		// 获取物料状态样式
		getMaterialStatusClass(status) {
			return status ? 'material-status-active' : 'material-status-inactive';
		},
		// 获取物料状态文本
		getMaterialStatusText(status) {
			return status ? '是' : '否';
		},

		handleScanWeigh() {
			console.log('scanCode')
			scanCodeUtils().then(res => {
				console.log(res)
				this.queryStatus(res.code)
			}).catch(err => {
				console.log(err)
				toast(err.message || '扫码失败')
			})

		},
		handleSearchCode() {
			this.showPopup = true
		},

		onConfirm(value) {
			console.log('输入的内容：', value);
			this.showPopup = false
			this.queryStatus(value)
		},
		onClose() {
			console.log('弹窗关闭');
			this.showPopup = false
		},

		// 检测设备类型
		checkDeviceType() {
			const systemInfo = uni.getSystemInfoSync();
			this.isTablet = systemInfo.screenWidth >= 768 || systemInfo.deviceType === 'tablet';
		},

		queryWorkDetailinfo(workId) {
			this.Loading = true
			this.data = {}
			this.weighingMasterListFinished = []
			getWorkDetail(workId).then(res => {
				// console.log(res.data, " res.data");
				this.Loading = false
				this.data = res.data
				this.weighingMasterList = res.data.weighingMasterList[0]
				this.weighingMasterListFinished = res.data.weighingMasterListFinished
			}).catch(err => {
				this.Loading = false
				console.log('获取详情失败，使用默认数据');
			})
		},

		queryStatus(materialId) {
			this.Loading = true
			this.userAdmin = true
			this.showTosdata = null
			this.detailsId = materialId
			getcheckSubMaterial(this.workId, materialId).then(res => {

				if (res.data.upper !== '/' && res.data.lower !== '/') {
					this.showTosdata = `( ${res.data.lower} - ${res.data.upper} )`
				}

				console.log(res)
				this.$store.dispatch('weight/updateWeight', String(0))
				this.$store.dispatch('weight/updateWeightStr', String(0))
				this.Loading = false
				this.materialInfo = res.data
				this.showInfoPopup = true

			}).catch(err => {
				console.log(err)
				this.Loading = false
				toast(err.msg | '查询失败')
			})
		},
		pasTime(str) {
			console.log(str, "str");
			// 将输入转换为数字（处理字符串时间戳）
			const timestamp = String(str);

			// 方法1：字符串分割
			const year = timestamp.substring(0, 4);
			const month = timestamp.substring(4, 6);
			const day = timestamp.substring(6, 8);

			return new Date(`${year}-${month}-${day}`).toLocaleDateString();
		},

		cuQuantity(arr) {
			if (!Array.isArray(arr) || arr.length === 0 || !arr[0]) {
				return '---';
			}
			// console.log(arr[0], " arr[0]");
			return arr[0];
		},

		uploadWeight(weight) {
			this.Loading = true
			const data = {
				billNo: this.workId,
				materialId: this.detailsId,
				weight: weight,
			}
			updateCurrentWeight(data).then(res => {
				console.log(res);
				this.Loading = false
				if (res.code == 200) {
					this.showInfoPopup = false
					toast("提交成功")
					this.queryWorkDetailinfo(this.workId);
				} else {
					toast(res.msg | "提交失败")
					this.queryWorkDetailinfo(this.workId);
				}
			}).catch(err => {
				this.showInfoPopup = false
				console.log(err);
				this.Loading = false
				toast(err.msg | "提交失败")
			})
		},
		uploadWeights(weight, userId, userName) {
			this.Loading = true
			const data = {
				billNo: this.workId,
				materialId: this.detailsId,
				weight: weight,
				authorizerPersonId: userId,
				authorizerPersonName: userName
			}
			updateCurrentWeight(data).then(res => {
				console.log(res);
				this.Loading = false
				if (res.code == 200) {
					this.showInfoPopup = false
					toast("提交成功")
					this.queryWorkDetailinfo(this.workId);
				} else {
					toast(res.msg | "提交失败")
					this.queryWorkDetailinfo(this.workId);
				}
			}).catch(err => {
				this.showInfoPopup = false
				console.log(err);
				this.Loading = false
				toast(err.msg | "提交失败")
			})
		},

		handleCollapseChange(e) {
			this.weighingMasterListFinishedDetail = []
			console.log('折叠状态变化:', e, this.valueCollapse)
			this.queryaddWeighingDetail(e)
		},


		queryaddWeighingDetail(id) {
			this.tabloading2 = true
			addWeighingDetail(id).then(res => {
				console.log(res)
				this.tabloading2 = false
				this.weighingMasterListFinishedDetail = res.data.details
				console.log(this.weighingMasterListFinishedDetail, "this.weighingMasterListFinishedDetail");
			}).catch(err => {
				this.tabloading2 = false
				console.log(err);
			})
		},

		infoClose() {
			this.showInfoPopup = false
		},

		handleConfirm(e) {
			// 参数验证
			if (!e || typeof e !== 'object') {
				console.error('无效的参数:', e)
				toast('参数错误')
				return
			}

			const {
				unitId,
				subMaterialId,
				weight
			} = e

			// 检查必要参数
			if (!subMaterialId || weight === undefined || weight === null) {
				console.error('缺少必要参数:', {
					subMaterialId,
					weight
				})
				toast('缺少必要参数')
				return
			}

			console.log('称重确认参数:', e)

			try {
				// 单位转换 - 克转千克
				let finalWeight = parseFloat(weight)
				if (isNaN(finalWeight)) {
					toast('重量格式错误')
					return
				}

				if (unitId == 'G' || unitId == 'g') {
					finalWeight = finalWeight //* 1000
				}

				// 构建请求数据
				const requestData = {
					subMaterialId,
					weight: finalWeight,
				}

				// 如果有单据号，添加到请求数据中
				if (this.weighingMasterList?.billNo) {
					requestData.billNo = this.weighingMasterList.billNo
				}

				// 检查称重权限
				getcheckWeighingWeigh(requestData)
					.then(res => {
						if (!res?.data) {
							throw new Error('响应数据格式错误')
						}

						this.userAdmin = res.data.flag

						if (this.userAdmin) {
							this.uploadWeight(finalWeight)
						} else {
							toast('当前重量不在规定范围内')
						}
					})
					.catch(err => {
						console.error('获取称重权限失败:', err)
						const errorMsg = err?.msg || err?.message || '获取称重权限失败'
						toast(errorMsg)
					})

			} catch (error) {
				console.error('处理称重确认时发生错误:', error)
				toast('处理称重数据时发生错误')
			}
		},
		handleConfirms(e) {
			// 参数验证
			if (!e || typeof e !== 'object') {
				console.error('无效的参数:', e)
				toast('参数错误')
				return
			}

			const {
				unitId,
				subMaterialId,
				weight,
				userInfo
			} = e

			// 检查必要参数
			if (!subMaterialId || weight === undefined || weight === null) {
				console.error('缺少必要参数:', {
					subMaterialId,
					weight
				})
				toast('缺少必要参数')
				return
			}

			console.log('称重确认参数:', e)

			try {
				// 重量转换和验证
				let finalWeight = parseFloat(weight)
				if (isNaN(finalWeight) || finalWeight <= 0) {
					toast('重量格式错误或必须大于0')
					return
				}

				// 单位转换 - 克转其他单位
				if (unitId === 'G' || unitId === 'g') {
					finalWeight = finalWeight //* 1000
				}

				// 构建请求数据
				const requestData = {
					subMaterialId,
					weight: finalWeight, // 使用转换后的重量
				}

				// 如果有单据号，添加到请求数据中
				if (this.weighingMasterList?.billNo) {
					requestData.billNo = this.weighingMasterList.billNo
				}

				console.log('最终请求数据:', requestData)

				// 检查称重权限
				getcheckWeighingWeigh(requestData)
					.then(res => {
						if (!res?.data) {
							throw new Error('响应数据格式错误')
						}
						// 注意：这里应该是 res.data.flag 或其他字段，根据实际API调整
						if (!res.data.flag) { // 假设 flag 为 true 表示有权限
							// 没有权限时需要用户认证
							if (!userInfo?.userId || !userInfo?.passWord) {
								toast('需要管理员认证但认证信息不全')
								return
							}

							updateCurrentWeightUser(userInfo.userId, userInfo.passWord)
								.then(authRes => {
									if (authRes?.data) {
										this.uploadWeights(finalWeight, userInfo.userId, userInfo
											.userName) // 使用转换后的重量
									} else {
										toast('认证失败')
									}
								})
								.catch(err => {
									console.error('更新用户重量失败:', err)
									toast(err.msg || '管理员认证失败')
								})
						}
					})
					.catch(err => {
						console.error('获取称重权限失败:', err)
						const errorMsg = err?.msg || err?.message || '获取称重权限失败'
						toast(errorMsg)
					})

			} catch (error) {
				console.error('处理称重确认时发生错误:', error)
				toast('处理称重数据时发生错误')
			}
		},
		onPasswordChange(password) {
			console.log('密码变更:', password)
			this.userInfo.passWord = password
		},

		onUserChange(user) {
			console.log('用户变更:', user)
			this.userInfo = {
				...user
			}
		},

		onUserInfoUpdate(userInfo) {
			console.log('用户信息更新:', userInfo)
			// 同步更新本地用户信息
			this.userInfo = {
				...userInfo
			}
		},
		changeCollapse(e) {
			console.log(e);
		},
		/**
		 * 将格林威治时间字符串转换为中国时间
		 * @param {string} gmtTime - 格林威治时间字符串，格式如：20251127174332
		 * @param {Object} options - 可选参数
		 * @param {boolean} options.includeTime - 是否包含时间部分，默认true
		 * @param {string} options.separator - 日期时间分隔符，默认空格
		 * @returns {string} 格式化后的中国时间字符串
		 */
		convertGMTToChinaTime(timeStr, options = {}) {


			let gmtTime = String(timeStr)

			const {
				includeTime = true,
				separator = ' '
			} = options;
			// 验证输入格式
			if (!gmtTime || typeof gmtTime !== 'string' || gmtTime.length !== 14) {
				return '-'
			}

			// 解析时间字符串
			const year = gmtTime.substring(0, 4);
			const month = gmtTime.substring(4, 6);
			const day = gmtTime.substring(6, 8);
			const hour = gmtTime.substring(8, 10);
			const minute = gmtTime.substring(10, 12);
			const second = gmtTime.substring(12, 14);

			// 创建UTC时间对象
			const utcDate = new Date(Date.UTC(
				parseInt(year),
				parseInt(month) - 1, // 月份从0开始
				parseInt(day),
				parseInt(hour),
				parseInt(minute),
				parseInt(second)
			));

			// 转换为中国时间（UTC+8）
			const chinaTime = new Date(utcDate.getTime() + 0 * 60 * 60 * 1000);

			// 格式化输出
			if (includeTime) {
				return this.formatDateTime(chinaTime, separator);
			} else {
				return this.formatDate(chinaTime);
			}
		},

		/**
		 * 格式化日期时间
		 * @param {Date} date - 日期对象
		 * @param {string} separator - 分隔符
		 * @returns {string} 格式化后的日期时间字符串
		 */
		formatDateTime(date, separator = ' ') {
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			const hour = String(date.getHours()).padStart(2, '0');
			const minute = String(date.getMinutes()).padStart(2, '0');
			const second = String(date.getSeconds()).padStart(2, '0');

			return `${year}-${month}-${day}${separator}${hour}:${minute}:${second}`;
		},

		/**
		 * 仅格式化日期部分
		 * @param {Date} date - 日期对象
		 * @returns {string} 格式化后的日期字符串
		 */
		formatDate(date) {
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');

			return `${year}-${month}-${day}`;
		}

	},
}
</script>

<style lang="scss" scoped>
page {
	background-color: #ffffff;
}

.container {
	padding: 20rpx;
	box-sizing: border-box;

	&.tablet-layout {
		padding: 30rpx;
		margin: 0 auto;
	}
}

.header-card {
	background: linear-gradient(135deg, #007AFF, #0056CC);
	border-radius: 16rpx;
	padding: 20rpx 20rpx;
	color: white;
	margin-bottom: 15rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 122, 255, 0.3);

	.tablet-layout & {
		margin-bottom: 20rpx;
		padding: 30rpx 20rpx;
	}
}

.header-card-a {
	border-radius: 16rpx;
	color: white;
	margin-bottom: 15rpx;

	.tablet-layout & {
		margin-bottom: 10rpx;
		padding: 20rpx 20rpx;
	}
}

.header-card-c {
	background: #ffffff;
	border-radius: 16rpx;
	padding: 40rpx 30rpx;
	color: white;
	margin-bottom: 15rpx;
	// box-shadow: rgba(0, 0, 0, 0.15) 1.95px 1.95px 2.6px;

	.tablet-layout & {
		margin-bottom: 20rpx;
		padding: 10rpx 20rpx;
	}
}

.header-top {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
}

.title-section {
	flex: 1;
}

.main-title {
	display: block;
	font-size: 36rpx;
	font-weight: bold;
	margin-bottom: 10rpx;
}

.sub-title {
	font-size: 28rpx;
	opacity: 0.9;
}

.status-badge {
	padding: 8rpx 20rpx;
	border-radius: 20rpx;
	font-size: 24rpx;
	font-weight: bold;
	background: rgba(255, 255, 255, 0.2);
}

.basic-info-grid {
	display: flex;
	justify-content: flex-start;
	gap: 30rpx;

	.tablet-layout & {
		gap: 15rpx;
	}
}

.basic-info-item {
	display: flex;
	flex-direction: column;
	gap: 8rpx;
	margin-right: 15rpx;
}

.basic-info-label {
	font-size: 28rpx;
	opacity: 0.8;
	color: #000000;
}

.basic-info-value {
	font-size: 28rpx;
	font-weight: 500;
}

// 表格样式
.material-table-container {
	background: white;
	border-radius: 16rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
	padding-top: 10rpx;
}

.table-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.table-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.table-count {
	font-size: 26rpx;
	color: #666;
}

// 自定义表格样式
::v-deep .uni-table {
	width: 100%;
	font-size: 24rpx;
}

::v-deep .uni-table-th {
	background-color: #f8f9fa !important;
	font-weight: bold;
	color: #333;
	padding: 15rpx;
}

::v-deep .uni-table-td {
	padding: 15rpx;
	color: #666;
}

::v-deep .uni-table-tr {
	border-bottom: 1rpx solid #f0f0f0;
}

::v-deep .uni-table-striped .uni-table-tr:nth-child(even) {
	background-color: #f8f9fa;
}

.status-tag {
	padding: 4rpx 12rpx;
	border-radius: 12rpx;
	font-size: 22rpx;
	font-weight: 500;
	display: inline-block;
}

.material-status-active {
	background: #34C759;
	color: white;
}

.material-status-inactive {
	background: #999;
	color: white;
}

.value-highlight {
	color: #007AFF;
	font-weight: bold;
}

.btn {
	display: flex;
	align-items: center;
	justify-content: center;
	border: none;
	border-radius: 8rpx;
}

.btn-xs {
	padding: 0 20rpx;
	font-size: 22rpx;
}

.btn-primary {
	background: #007AFF;
	color: white;
}

.btn-primary:disabled {
	background: #CCCCCC;
	color: #999;
}

.btn-secondary {
	background: #F8F8F8;
	color: #007AFF;
	border: 2rpx solid #007AFF;
}

.action-buttons {
	display: flex;

	&.tablet-buttons {
		margin-left: auto;
		margin-right: auto;
	}

	.btn {
		flex: 1;
		font-size: 32rpx;
	}
}

.header-card-c {
	background: white;
	border-radius: 16rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
	// box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.button-group {
	display: flex;
	justify-content: flex-start;
	align-items: center;
}

.btn {
	display: flex;
	align-items: center;
	justify-content: center;
	border: none;
	border-radius: 12rpx;
	flex: 1;
	transition: all 0.3s ease;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
	max-width: 220rpx;
	margin: 0;
	margin-right: 20rpx;
	padding: 0;
}

.btn-c {
	display: flex;
	align-items: center;
	justify-content: center;
	border: none;
	border-radius: 12rpx;
	flex: 1;
	transition: all 0.3s ease;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
	max-width: 230rpx;
	margin: 0;
	margin-right: 20rpx;
	padding: 0;
}

.btn-primary {
	background: linear-gradient(135deg, #FF6B6B, #FF8E8E);
	color: white;
}

.btn-primary:active {
	background: linear-gradient(135deg, #FF5252, #FF7B7B);
	transform: translateY(2rpx);
	box-shadow: 0 2rpx 8rpx rgba(255, 107, 107, 0.4);
}

.btn-secondary {
	background: linear-gradient(135deg, #4ECDC4, #6EE7E7);
	color: white;
}

.btn-secondary:active {
	background: linear-gradient(135deg, #26A69A, #4ECDC4);
	transform: translateY(2rpx);
	box-shadow: 0 2rpx 8rpx rgba(78, 205, 196, 0.4);
}

.btn-refresh {
	width: 60rpx;
	height: 60rpx;
	border: none;
	border-radius: 50%;
	background: linear-gradient(135deg, #cecece, #cecece);
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 4rpx 12rpx rgba(255, 167, 38, 0.3);
	transition: all 0.3s ease;
	flex-shrink: 0;
	margin: 0;
	margin-left: auto;
}

.example-body {
	flex-direction: column;
	flex: 1;
}

.content {
	padding: 15px;
	padding-top: 0;
}

.text {
	font-size: 14px;
	color: #666;
	line-height: 20px;
}

.button {
	// margin-top: 10px;
	margin: 10px;
	margin-bottom: 0;
}


.data_null {
	padding: 50rpx 0;
	height: 50rpx;
	background-color: #e9e9e9;
	font-size: 32rpx;
	color: #000000;
	display: flex;
	align-items: center;
	justify-content: center;
}
</style>